let WebSocketServer = require('websocket').server;
let WebSocketClient = require('websocket').client;
let WebSocketFrame = require('websocket').frame;
let WebSocketRouter = require('websocket').router;
let W3CWebSocket = require('websocket').w3cwebsocket;

var http = require('http');
require('./model')
let talk = require('./talk.js')
var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8082, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
    return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
        // Make sure we only accept requests from an allowed origin
        request.reject();
        console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');

        return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    let temp = null

    talk.find({}, { name: 1, msg: 1, _id: 0 }).then(value => {
        temp = value
        connection.sendUTF(value);
        // console.log(Object.keys(connection, 77))
    })


    connection.on('message', async function(message) {
        console.log(message)

        await talk.create({
            name: 'me',
            msg: message.utf8Data
        }).then(value => {
            console.log(value)

        })
        clearTimeout(time)
        let time = setInterval(() => {
            talk.find({}, { name: 1, msg: 1, _id: 0 }).then(value => {
                if (value.length != temp.length) {
                    temp = value
                    connection.sendUTF(value);
                }
                // console.log(456464)
                // console.log(Object.keys(connection, 77))
            })
        }, 100);
        // if (message.type === 'utf8') {
        //     console.log('Received Message: ' + message.utf8Data);
        //     connection.sendUTF(message.utf8Data);
        // } else if (message.type === 'binary') {
        //     console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        //     connection.sendBytes(message.binaryData);
        // }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

// "@electron-forge/cli": "^6.0.0-beta.57",
// "@electron-forge/maker-deb": "^6.0.0-beta.57",
// "@electron-forge/maker-rpm": "^6.0.0-beta.57",
// "@electron-forge/maker-squirrel": "^6.0.0-beta.57",
// "@electron-forge/maker-zip": "^6.0.0-beta.57",
// "websocket": "^1.0.34""electron-reloader": "^1.2.1"